package com.future.interview;

/**
 * Description: 面试题67. 把字符串转换成整数
 * 输入: "4193 with words"
 * 输出: 4193
 * 解释: 转换截止于数字 '3' ，因为它的下一个字符不为数字。
 *
 * @author weiruibai.vendor
 * Date: 2023/1/17 09:43
 */
public class Solution_67 {

    private static Solution_67 instance = new Solution_67();

    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
        System.out.println((int) (3.14159));
        System.out.println("===================");
        String str = "4193 with words";

        str = "21474836460";
        str = "   -42";
        str = "words and 987";
        str = "-91283472332";
        str = "3.14159";
        str = "+-12";
        str = "-+1";
        System.out.println(instance.strToInt(str));
    }

    /**
     * 1、+ - 字符连续时，返回0
     * 2、只忽略前缀空格，遇到第一个'+'或者'-' 紧接着时数字或者"."(小数点)，只要出现空格、字符等就结束
     *
     * @param str
     * @return
     */
    public int strToInt(String str) {
        int ans = 0;
        boolean startSym = false;
        boolean startNum = false;
        boolean positive = true;// 是否是正数
        StringBuilder sb = new StringBuilder();
        for (char ch : str.toCharArray()) {
            if (ch == '-') {
                if (startSym || startNum) break;
                startSym = true;
                positive = false;
            } else if (ch == '+') {
                if (startSym || startNum) break;
                startSym = true;
                positive = true;
            } else if (Character.isDigit(ch) || ch == '.') {
                // 数字
                sb.append(ch);
                startNum = true;
            } else if (Character.isLetter(ch) || ((startNum || startSym) && ch == ' ')) {
                // 字符，直接退出
                break;
            }
        }
        String s = sb.toString();
        if ("".equals(s)) {
            return 0;
        }
        Double aLong = Double.valueOf(s);
        if (!positive) {
            aLong = -aLong;
        }
        if (aLong > Integer.MAX_VALUE) {
            ans = Integer.MAX_VALUE;
        } else if (aLong < Integer.MIN_VALUE) {
            ans = Integer.MIN_VALUE;
        } else {
            ans = aLong.intValue();
        }
        return ans;
    }
}
